package com.somsoft.handjc.activity.setting;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.http.util.EncodingUtils;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.somsoft.handjc.activity.R;
import com.somsoft.handjc.util.BaseActivity;
import com.somsoft.handjc.util.MyApplication;
import com.somsoft.handjc.util.Utils;

public class SetIpActivity extends BaseActivity {
	private Button btnOk = null;
	private EditText etIp = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.getInstance().addActivity(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.setip);
		btnOk = (Button)findViewById(R.id.setip_button);
		etIp = (EditText)findViewById(R.id.setip_edit);
		btnOk.setOnClickListener(new OnClickListenerImpl());
		try {
			etIp.setText(readFileData("ip.txt"));
		} catch (Exception e) {
//			Toast.makeText(SetIpActivity.this, "读取配置文件失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	private class OnClickListenerImpl implements OnClickListener{

		@Override
		public void onClick(View v) {
			try {
				writeFileData("ip.txt",etIp.getText().toString());
				Utils.SERVER_IP = etIp.getText().toString();
				Toast.makeText(SetIpActivity.this, "IP修改成功", Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				Toast.makeText(SetIpActivity.this, "IP修改失败", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public void writeFileData(String fileName, String message) throws Exception{
		try {
			FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
			byte[] bytes = message.getBytes();
			fout.write(bytes);
			fout.close();
		} catch (Exception e) {
			throw e;
		}
	}
	
	public String readFileData(String fileName) throws Exception{
		String res = "";
		try {
			FileInputStream fin = openFileInput(fileName);
			int length = fin.available();
			byte[] buffer = new byte[length];
			fin.read(buffer);
			res = EncodingUtils.getString(buffer, "UTF-8");
			fin.close();
		}catch (Exception e) {
			throw e;
		}
		return res;
	}

}